<template>
  <div class="model-list-container">
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <a-button @click="handleCreate" type="primary"> 新增 </a-button>
        <a-button class="ml-2" @click="handleImport()"> 导入 </a-button>
        <ButtomImport @register="rgImport" @beforeUpload="handleImportJson" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '导入',
                onClick: handleImport.bind(null, record.modelCode),
              },
              {
                label: '导出',
                onClick: handleExport.bind(null, record),
              },
              {
                label: '删除',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <ModelDesignDrawer :classify="1" @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  // import { Button } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { ButtomImport, useButtomImport } from '/@/components/ImportButton';

  import { useMessage } from '/@/hooks/web/useMessage';
  // import { useGo } from '/@/hooks/web/usePage';
  import { downloadByUrl, setEncoded } from '/@/utils/file/download';

  import {
    getModelByListApi,
    delModelApi,
    getModelInfoApi,
    importModelApi,
    MODEL_TYPE,
  } from '/@/api/config-center/model-design';
  import { columns, searchFormSchema } from './design.data';
  import { useDrawer } from '/@/components/Drawer';
  import ModelDesignDrawer from '../model-design/index.vue';

  export default defineComponent({
    name: 'ModelList',
    components: { BasicTable, ModelDesignDrawer, TableAction, ButtomImport },
    setup() {
      const { createMessage } = useMessage();
      // const go = useGo();

      const [registerTable, { reload }] = useTable({
        api: getModelByListApi,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        useSearchForm: true,
        showTableSetting: false,
        bordered: false,
        // showIndexColumn: false,
        actionColumn: {
          width: 220,
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
        },
      });

      const [registerDrawer, { openDrawer }] = useDrawer();
      const [rgImport, { importFile }] = useButtomImport();

      function handleCreate() {
        // go('/config-center/model-form/index');

        openDrawer(true, {
          isUpdate: false,
          openDrawer: {},
        });
      }

      function handleEdit(record: Recordable) {
        // go({
        //   path: '/config-center/model-form/index',
        //   query: {
        //     id: record.modelId,
        //   },
        // });

        openDrawer(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable) {
        await delModelApi(record.modelId);
        createMessage.success('操作成功');
        reload();
      }

      function handleSuccess() {
        reload();
      }
      let currModelCode = '';

      async function handleImport(modelCode = '') {
        currModelCode = modelCode;
        await importFile();
      }

      async function handleImportJson(jsonStr) {
        const editorJsonData = JSON.parse(jsonStr);
        if (editorJsonData.classify !== MODEL_TYPE.LIST)
          return createMessage.warn('导入失败，请使用列表模型的数据格式');
        if (currModelCode) {
          editorJsonData.modelCode = currModelCode;
        }
        try {
          await importModelApi(editorJsonData);
          createMessage.success('导入成功');
          reload();
        } catch (e) {
          throw e;
        }
      }
      async function handleExport({ modelName, modelCode, modelId }) {
        const data = await getModelInfoApi(modelId as string);
        const json = JSON.stringify(data);
        const { href, filename } = setEncoded('JSON', modelName + '_' + modelCode, json!);

        downloadByUrl({ url: href, fileName: filename });
      }

      return {
        registerTable,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleImport,
        handleExport,
        registerDrawer,
        rgImport,
        handleImportJson,
      };
    },
  });
</script>
